from django.shortcuts import *
from .models import Book

def allbook(request):
    books = Book.objects.all()
    context = {
        'books':books
    }
    return render(request,'allbook.html',context=context)
def addbook(request):
    if request.method == 'GET':
        return render(request,'addbook.html')
    else:
        name = request.POST.get('name')
        author = request.POST.get('author')
        price = request.POST.get('price')
        book = Book(name=name,author=author,price=price)
        book.save()
        return redirect(reverse('allbook'))
def delete(request,bookid):
    book = Book.objects.get(pk = bookid)
    book.delete()
    return redirect(reverse('allbook'))

def update(request,bookid):
    if request.method == 'GET':
        book = Book.objects.get(pk=bookid)
        context = {
            'book':book
        }
        return render(request,'update.html',context=context)
    else:
        name = request.POST.get('name')
        author = request.POST.get('author')
        price = request.POST.get('price')
        book = Book.objects.get(pk=bookid)
        if name == "":
            pass
        else:
            book.name=name

        if author == "":
            pass
        else:
            book.author=author

        if price == "":
            pass
        else:
            book.price=price
        book.save()
        return redirect(reverse('allbook'))

